package sample.service.article.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sample.intf.article.dao.IArticleDao;
import sample.intf.article.dao.IArticlePictureDao;
import sample.intf.article.dto.TArticle;
import sample.intf.article.dto.TArticlePicture;
import sample.intf.article.service.IArticleService;

@Service
public class ArticleService implements IArticleService {

	@Autowired
	IArticleDao articleDao;

	@Autowired
	IArticlePictureDao articlePictureDao;

	@Override
	public TArticle selectArticle(long id) {
		return articleDao.selectArticle(id);
	}

	@Override
	public List<TArticle> selectAllArticles() {
		return articleDao.selectAllArticles();
	}

	@Override
	public void insertArticle(TArticle article) {
		articleDao.insertArticle(article);
	}

	@Override
	public boolean updateArticle(TArticle article) {
		return articleDao.updateArticle(article);
	}

	@Override
	public void deleteArticle(long id) {
		articleDao.deleteArticle(id);
	}

	@Override
	public List<TArticlePicture> selectMissingArticlePictures(long articleId, List<String> guids) {
		return articlePictureDao.selectMissingArticlePictures(articleId, guids);
	}

	@Override
	public void addArticlePicture(TArticlePicture articlePicture) {
		articlePictureDao.insertArticlePicture(articlePicture);
	}

	@Override
	public void saveArticlePicture(TArticlePicture articlePicture, String rootPath, byte[] imageData,
			boolean alsoAddToDatabase) throws IOException {
		File file = new File(rootPath, articlePicture.getPath());
		FileUtils.writeByteArrayToFile(file, imageData, false);
		articlePictureDao.insertArticlePicture(articlePicture);
	}

	@Override
	public void deleteArticlePictures(long articleId, String rootPath) {
		List<TArticlePicture> pictures = articlePictureDao.selectArticlePictures(articleId);
		for (TArticlePicture eachPicture : pictures) {
			File file = new File(rootPath, eachPicture.getPath());
			try {
				if (file.exists())
					file.delete();
			} catch (Exception e) {
				// Do nothing
			}
		}
		articlePictureDao.deleteArticlePictures(articleId);
	}

	@Override
	public void deleteArticlePictures(List<TArticlePicture> pictures, String rootPath) {
		ArrayList<String> guids = new ArrayList<>();
		for (TArticlePicture eachPicture : pictures) {
			File file = new File(rootPath, eachPicture.getPath());
			try {
				if (file.exists())
					file.delete();
			} catch (Exception e) {
				// Do nothing
			}
			guids.add(eachPicture.getGuid());
		}
		articlePictureDao.deleteArticlePictures(guids);
	}
}
